package com.validator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.validator.config.ConfigProperties;
import com.validator.dao.EquipmentTypeDao;
import com.validator.dao.LargessDao;
import com.validator.entity.EquipmentType;
import com.validator.entity.Largess;
import com.validator.service.IFileUploaderService;
import com.validator.util.Result;
import com.validator.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FileUploaderServiceImpl implements IFileUploaderService {
    private static final Logger log = LoggerFactory.getLogger(FileUploaderServiceImpl.class);

    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private EquipmentTypeDao equipmentTypeDao;
    @Autowired
    private LargessDao largessDao;

    @Override
    public Result<Boolean> bgUploader(String fileName, MultipartFile multipartFile) {
        if (StringUtil.isBlank(fileName)) {
            return Result.fail(501, "文件名称不能为空");
        }
        if (multipartFile == null || multipartFile.isEmpty()) {
            return Result.fail(502, "上传文件为空");
        }
        try {
            File dir = new File(configProperties.getBgDirPath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            multipartFile.transferTo(new File(configProperties.getBgDirPath() + File.separator + fileName));
        } catch (IOException e) {
            log.error("bgUploader error: \r\n", e);
            return Result.fail(503, "文件存储失败，请重试");
        }
        return Result.ok(Boolean.TRUE);
    }

    @Override
    public Result<Boolean> largessUploader(int equipmentId, String fileFormat, String name, MultipartFile multipartFile) {
        if (StringUtil.isBlank(fileFormat)) {
            return Result.fail(501, "文件格式不能为空");
        }
        if (StringUtil.isBlank(name)) {
            return Result.fail(501, "赠品名称不能为空");
        }

        EquipmentType equipmentType = equipmentTypeDao.selectById(equipmentId);
        if (equipmentType == null) {
            return Result.fail(502, "不存在的设备类型");
        }

        if (multipartFile == null || multipartFile.isEmpty()) {
            return Result.fail(503, "上传图片为空");
        }

        String filePath = configProperties.getFileServerPath() + File.separator + equipmentType.getType() + '.' + fileFormat;
        try {
            File dir = new File(configProperties.getFileServerPath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            multipartFile.transferTo(new File(filePath));
        } catch (Exception e) {
            log.error("largessUploader error: \r\n", e);
            return Result.fail(504, "图片保存失败，请重试");
        }
        String imgUrl = configProperties.getServerIp() + equipmentType.getType() + '.' + fileFormat;
        try {
            QueryWrapper<Largess> largessQueryWrapper = new QueryWrapper<>();
            largessQueryWrapper.eq("equipmentId", equipmentId);
            List<Largess> largesses = largessDao.selectList(largessQueryWrapper);
            if (largesses != null && !largesses.isEmpty()) {
                if (largesses.size() > 1) {
                    List<Integer> ids = new ArrayList<>();
                    for (Largess largess : largesses) {
                        ids.add(largess.getId());
                    }
                    largessDao.deleteBatchIds(ids);
                    Largess largess = new Largess();
                    largess.setEquipmentId(equipmentId);
                    largess.setName(name);
                    largess.setCreateTime(new Date());
                    largess.setImgPath(imgUrl);
                    largessDao.insert(largess);
                } else {
                    Largess largess = largesses.get(0);
                    largess.setImgPath(imgUrl);
                    largess.setName(name);
                    largessDao.updateById(largess);
                }
            } else {
                Largess largess = new Largess();
                largess.setEquipmentId(equipmentId);
                largess.setCreateTime(new Date());
                largess.setName(name);
                largess.setImgPath(imgUrl);
                largessDao.insert(largess);
            }

        } catch (Exception e) {
            log.error("largessUploader error: \r\n", e);
            return Result.fail(504, "图片保存失败，请重试");
        }

        return Result.ok(Boolean.TRUE);
    }


    @Override
    public Result<List<Largess>> listAllEquipmentLargess() {
        return Result.ok(largessDao.selectList(null));
    }

    @Override
    public Result<Largess> getLargessByEquipmentId(int equipmentId) {
        if (equipmentId <= 0) {
            return Result.fail(501, "不存在的设备");
        }

        EquipmentType equipmentType = equipmentTypeDao.selectById(equipmentId);
        if (equipmentType == null) {
            return Result.fail(501, "不存在的设备");
        }

        QueryWrapper<Largess> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("equipmentId", equipmentId);
        Largess largess = largessDao.selectOne(queryWrapper);
        if (largess == null) {
            return Result.fail(502, "未查询到赠品");
        }

        return Result.ok(largess);
    }
}
